package com.hhdys.service;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.hhdys.constant.Env;
import com.hhdys.utils.HttpHelper;

public class TokenService {
	
	private static final Logger log=LogManager.getLogger(TokenService.class);
	/**
	 * token
	 */
	private static String token=null;
	/**
	 * 默认token无效
	 */
	private static boolean tokenIsValid=false;
	/**
	 * 上一次获取token的时间
	 */
	private static long tokenTime=0L;
	
	static{
		getAccessToken();
	}
	
	/**
	 * token失效，重新获取
	 */
	private static void accessTokenIsInValid(){
		String corpId=Env.corpId;
		String corpSecret=Env.corpSecret;
		String accessTokenUrl=Env.accessTokenUrl;
		if(StringUtils.isEmpty(corpId)||StringUtils.isEmpty(corpSecret)||StringUtils.isEmpty(accessTokenUrl)){
			log.error("corpId:{} or corpSecret:{} or accessTokenUrl:{} can not be empty!!!",corpId,corpSecret,accessTokenUrl);
			return ;
		}
		String url=String.format(accessTokenUrl, corpId,corpSecret);
		log.info("accessTokenUrl is :{}",url);
		JSONObject result = HttpHelper.httpGet(url);
		if(result==null){
			log.info("get accessToken error:corpId:{} , corpSecret:{} , accessTokenUrl:{} ",corpId,corpSecret,accessTokenUrl);
			return ;
		}
		token=result.getString("access_token");
		tokenIsValid=true;
		tokenTime=System.currentTimeMillis();
	}
	/**
	 * 获取token
	 */
	public static String getAccessToken(){
		long now=System.currentTimeMillis();
		long timeLong=(now-tokenTime)/1000/60;
		boolean timeExpired=timeLong>100;
		log.info("timeExipred is:{},timeLong:{}",timeExpired,timeLong);
		if(timeExpired||!tokenIsValid){
			synchronized (TokenService.class) {
				if(timeExpired||!tokenIsValid){
					log.info("get accessToken,timeExpired:{},tokenIsValid:{}",timeExpired,tokenIsValid);
					accessTokenIsInValid();
				}
			}
		}
		return token;
	}
	/**
	 * 将token设为无效
	 */
	public static void setTokenInvalid(){
		tokenIsValid=false;
		getAccessToken();//重新获取
	}
}
